package javaweb.oa.web.action;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import javaweb.oa.web.action.Utils.DBUtil;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DeptDeleteServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");

        String deptno = request.getParameter("deptno");
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;

        int count = 0;
        try{
            conn = DBUtil.getConnection();
            conn.setAutoCommit(false);
            String sql = "delete from dept where deptno = ?";
            ps = conn.prepareStatement(sql);
            ps.setString(1,deptno);
            count = ps.executeUpdate();

            //事务提交
            conn.commit();

        }catch (Exception e){
            if(conn!=null){
                try{
                    conn.rollback();
                }catch(SQLException e1){
                    e1.printStackTrace();
                }
            }
            e.printStackTrace();
        }finally{
            DBUtil.close(conn,ps,rs);
        }

        if(count!=0){
            //DeptListServlet list = new DeptListServlet();
            //list.doGet(request,response);
            //转发
            //request.getRequestDispatcher("/dept/list").forward(request,response);

            response.sendRedirect(request.getContextPath() + "/dept/list");
        }else{
            //request.getRequestDispatcher("/error.html").forward(request,response);

            response.sendRedirect(request.getContextPath() + "/error.html");
        }

    }
}
